package com.c6906.vdam.dps.config;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

public class YearRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> shardingValue) {
        Set<String> result = new LinkedHashSet<>();

        // 获取范围的起始值和结束值
        String lowerEndpoint = shardingValue.getValueRange().hasLowerBound() ? shardingValue.getValueRange().lowerEndpoint() : null;
        String upperEndpoint = shardingValue.getValueRange().hasUpperBound() ? shardingValue.getValueRange().upperEndpoint() : null;

        // 从 yyyy-MM-dd HH:mm:ss 格式的时间字符串中提取年份
        int lowerYear = lowerEndpoint != null ? Integer.parseInt(lowerEndpoint.substring(0, 4)) : 2024; // 默认起始年份
        int upperYear = upperEndpoint != null ? Integer.parseInt(upperEndpoint.substring(0, 4)) : 2025; // 默认结束年份

        // 遍历并选择符合范围的库
        for (String targetName : availableTargetNames) {
            // 从库名 vdamYYYY 中提取年份
            int targetYear = Integer.parseInt(targetName.replace("vdam", ""));
            if (targetYear >= lowerYear && targetYear <= upperYear) {
                result.add(targetName);
            }
        }

        return result;
    }
}
